#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@create Time:2018-11-28

@author:Brook
"""
import os
import re

import jieba
import fasttext


MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")

_analyzer = None


def process(line):
    new_line = " ".join(jieba.lcut(line))
    new_line = re.sub("\s[，。?？!！、\*~“”…;；（）《》‘’]", "", new_line).lower()
    return new_line


class SentimentAnalyzer:
    def __init__(self,clf):
        self.clf = clf 
        self.MIN_PROB = 0.1

    def __call__(self, text):
        assert isinstance(text, str)
        doc = process(text)
        y = self.clf.predict_proba([doc], k=5)
        for label, prob in y[0]:
            if prob < self.MIN_PROB:
                continue
            subject, value = label.replace("__label__", "").split("::")
            yield text, subject, value

    @classmethod
    def of_default(cls):
        model_path = os.path.join(MODEL_DIR, "clf.bin")
        clf = fasttext.load_model(model_path)
        return cls(clf)


def get_analyzer():
    global _analyzer
    if not _analyzer:
        _analyzer = SentimentAnalyzer.of_default()
    return _analyzer


if __name__ == "__main__":
    analyzer = get_analyzer()
    s = "就是呀，觉得对不起这个价格。开着烦心"
    for a,b,c in analyzer(s):
        print(a,b,c)
